import { useState, useCallback, useEffect, useRef } from "react"
import type { Banner } from "@/views/Discover/c-views/Recommend/api/type"
/* 
const openTimer = (timer: any, next: Function) => {
	timer = setInterval(() => {
		next()
	}, 3000)
}
const closeTimer = (timer: any) => {
	clearInterval(timer)
}
 const listener = (bannerRef: React.RefObject<HTMLAnchorElement>, timer: any, next: Function) => {
	if (!bannerRef.current) return
	const dom: HTMLAnchorElement = bannerRef.current
	dom.addEventListener("mouseenter", () => closeTimer(timer))
	dom.addEventListener("mouseleave", () => openTimer(timer, next))
}

const removeListener = (bannerRef: React.RefObject<HTMLAnchorElement>, timer: any, next: Function) => {
	if (!bannerRef.current) return
	const dom: HTMLAnchorElement = bannerRef.current
	dom.removeEventListener("mouseenter", () => closeTimer(timer))
	dom.removeEventListener("mouseleave", () => openTimer(timer, next))
} 
*/
const useCurrentHook = (banners: Banner[]) => {
	// 图片索引
	const [current, setCurrent] = useState<number>(0)
	// ref
	const bannerRef = useRef<HTMLAnchorElement>(null)
	// 图片切换
	const prev = useCallback(() => {
		if (current === 0) {
			setCurrent(banners.length - 1)
		} else {
			setCurrent(current - 1)
		}
	}, [current])
	const next = useCallback(() => {
		if (current === banners.length - 1) {
			setCurrent(0)
		} else {
			setCurrent(current + 1)
		}
	}, [current])
	let timer: any = null
	const openTimer = useCallback(() => {
		timer = setInterval(() => {
			next()
		}, 3000)
	}, [current])
	const closeTimer = useCallback(() => {
		clearInterval(timer)
	}, [current])

	useEffect(() => {
		openTimer()
		return () => {
			closeTimer()
		}
	}, [current])
	return {
		prev,
		next,
		current,
		setCurrent,
		bannerRef,
	}
}

export default useCurrentHook
